<template>
	<view class="">
		<view class="top-nav">
			<u-button type="" class="top-btn" :text="$t('buttonText.home')" @click="goToHomePage"
				style="width: 15%;"></u-button>
			<u-button type="" class="top-btn" :text="$t('buttonText.projection')" @click=""
				style="width: 15%;"></u-button>
			<image src="/static/lang_switcher.png" class="top-image" @click="chooseLanguage"></image>
		</view>

		<view class="" style="margin-top: 10px; border: 1px black solid;">
			<h4 style="margin-left: 15px;">{{ $t('textContent.animationSelection') }}</h4>
			<template>
				<view style="display: flex;">
					<uni-data-select v-model="value" :localdata="image" @change="changeIndex"
						placeholder="image"></uni-data-select>
					<uni-data-select v-model="value" :localdata="video" @change="changeIndex"
						placeholder="video"></uni-data-select>
					<uni-data-select v-model="value" :localdata="animation" @change="changeIndex"
						placeholder="animation"></uni-data-select>
				</view>
			</template>
			<u-alert :title="message" type="warning"></u-alert>
		</view>
		<view class="" style="width: 100%; display: flex;">

			<view style=" width: 60%; display: flex;justify-content: space-between;">
				<!-- 				<view class="" v-if="this.index==2">
					<SinWave @send="send"  :ref="this.index_name_map[this.index]"></SinWave>
				</view> -->
				<component :is="currentComponent" ref="dynamicChild" @send="send" /> 
			</view>
			<view class="right"
				style="width: 40%; display: flex; flex-direction: column; align-items: center; padding-right: 15px; padding-left: 15px;">
				<view class="" style="display: flex;width: 250px; ">
					<u-button type="primary" class="custom-style" :text="$t('buttonText.Start')"
						@click="callChildMethod(true,false)" style="margin-top: 15px;"></u-button>
					<u-button type="primary" class="custom-style" :text="$t('buttonText.Pause')"
						@click="callChildMethod(false,false)" style="margin-top: 15px;"></u-button>
					<u-button type="primary" class="custom-style" :text="$t('buttonText.End')" @click="callChildMethod(false,true)"
						style="margin-top: 15px;"></u-button>
				</view>

				<u-button type="primary" class="custom-style" :plain="true"
					:text="$t('buttonText.Controlterminalupdate')" @click="getZipFiles"
					style=" margin-top: 15px;width: 250px;"></u-button>
				<u-button type="primary" class="custom-style" style="margin-top: 15px;width: 250px;" @click="scanQrCode"
					:text="$t('buttonText.scanCodeIp')"></u-button>

				<u-button type="primary" class="custom-style" :text="$t('buttonText.Modifycommunicationaddress')"
					@click="changeIp" style="margin-top: 15px;width: 250px;"></u-button>
				<view class="" v-if="showIp == true">
					<view class="" style="border: 1px black solid;">
						<span>{{ $t('textContent.CommunicationIP') }}</span><input type="text"
							:placeholder="$t('buttonText.CommunicationIP')" v-model="ip" @blur="saveHostAndPort">
					</view>
					<view class="" style="border: 1px black solid;">
						<span>{{ $t('textContent.CommunicationPort') }}:</span><input type="text"
							:placeholder="$t('buttonText.CommunicationPort')" v-model="port" @blur="saveHostAndPort">
					</view>
				</view>
				<u-button type="primary" class="custom-style" :plain="true"
					:text="$t('buttonText.Projectionterminalupdate')" @click="update"
					style="margin-top: 15px;width: 250px;"></u-button>
				<u-button type="primary" class="custom-style" :plain="true"
					:text="$t('buttonText.Restartprojectionterminalapp')" @click="restart"
					style="margin-top: 15px;width: 250px;"></u-button>
				<u-button type="primary" class="custom-style" :plain="true"
					:text="$t('buttonText.Projectionterminalshutdown')" @click="shutdown"
					style="margin-top: 15px;width: 250px;"></u-button>
				<!-- 				<u-button type="primary" class="custom-style" :plain="true" :text="$t('buttonText.screenSet')"
					@click="screenSet" style="margin-top: 15px;width: 250px;"></u-button> -->
				<u-button type="primary" class="custom-style" :plain="true" :text="$t('buttonText.save_to_sql')"
					@click="showSaveSqlLite=true" style="margin-top: 15px;width: 250px;"></u-button>
				<view class="" v-if="showSaveSqlLite == true">
					<view class="" style="border: 1px black solid;">
						<span>{{$t('buttonText.save_plan_name')}}:</span><input type="text" v-model="planName"
							placeholder="...">
					</view>
					<view class="" style="border: 1px black solid;">
						<u-button type="primary" class="custom-style" :plain="true" :text="$t('save')"
							@click="saveToSqlLite(planName)"></u-button>
					</view>

				</view>
				<u-button type="primary" class="custom-style" :plain="true" :text="$t('buttonText.del_all_plan')"
					@click="btnDeleteAllSchema()" style="margin-top: 15px;width: 250px;"></u-button>
				<view class="" style="margin-top: 15px;width: 250px;" @click="getCurrentAllSchemas">
					<uni-data-select :localdata="cureentSchemas" @change="updateFromSchema"
						v-model='save_data_str'></uni-data-select>
				</view>

			</view>
		</view>
	</view>
	</view>
</template>

<script>
	// 定义 sleep 函数
	const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
	const crypto = require('crypto');
	import {
		type
	} from 'os';
	import {
		send
	} from 'process';
	import FC20230330, * as $FC20230330 from '@alicloud/fc20230330';
	import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
	import Util, * as $Util from '@alicloud/tea-util';
	import Stream from '@alicloud/darabonba-stream';
	import * as $tea from '@alicloud/tea-typescript';
	import {
		mediaAll,
		mediaIndexItem,
		mediaAdd,
		deleteAllSchemas,
		existSchema,
		mediaUpdate,
	} from "@/static/sql/media.js"
	import {
		sqlName,
		openDb,
		isOpened,
		closeDb,
		selectSql,
		executeSql
	} from "@/static/sql/sqllite.js"

	// 导入组件
	import ShapeGenerator from '@/components/animation/ShapeGenerator.vue'
	import SinWave from '@/components/animation/SinWave.vue'
	import XDistance from '@/components/animation/XDistance.vue'
	import CWave from '@/components/animation/CWave.vue'
	import Slalom from '@/components/animation/Slalom.vue'

	import Climbing from '@/components/image/Climbing.vue'
	import Grid from '@/components/image/Grid.vue'
	import Gridnum from '@/components/image/Gridnum.vue'
	import Maze from '@/components/image/Maze.vue'
	import Net from '@/components/image/Net.vue'
	import SingleCurve from '@/components/image/SingleCurve.vue'
	import SwichPractice from '@/components/image/SwichPractice.vue'
	import Track1 from '@/components/image/Track1.vue'
	import Track2 from '@/components/image/Track2.vue'

	import VideoStraight from '@/components/video/VideoStraight.vue'
	import ParallelTurn from '@/components/video/ParallelTurn.vue'
	import VideoCurve from '@/components/video/VideoCurve.vue'
	import WedgeTurn from '@/components/video/WedgeTurn.vue'
	import WedgeChristie from '@/components/video/WedgeChristie.vue'

	export default {
		components: {
			ShapeGenerator,
			SinWave,
			XDistance,
			CWave,
			Slalom,
			Climbing,
			Grid,
			Gridnum,
			Maze,
			Net,
			SingleCurve,
			SwichPractice,
			Track1,
			Track2,
			VideoStraight,
			ParallelTurn,
			VideoCurve,
			WedgeTurn,
			WedgeChristie
		},
		data() {
			return {
				cureentSchemas: [],
				planName: "",
				showSaveSqlLite: false,
				src: "",
				waveNum: 1,
				message: 'There is no message in the message queue yet',
				pollingInterval: null,
				timer: null,
				elapsed: 0, // 以毫秒为单位
				isRunning: false,
				timingValue: 'clear',
				language: 'chinese', // 添加language字段
				isBlack: false,
				LineBlack: false,
				isReverse: false,
				current: 0,
				showIp: false,
				ip: "10.168.0.105",
				// ip:"192.168.0.119",
				port: "12345",
				// shape_generator: this.$t('shape_generator'),
				// sinWave: this.$t('sinWave'),
				// curve: this.$t('curve'),
				// xDistance: this.$t('xDistance'),
				// cWave: this.$t('cWave'),
				// Slalom: this.$t('Slalom'),
				// parallelTurn: this.$t('parallelTurn'),
				index: 1,
				value: 1,
				image: [{
						value: 3,
						text: "Maze"
					},
					{
						value: 7,
						text: "Net"
					},
					{
						value: 8,
						text: "SingleCurve"
					},
					{
						value: 9,
						text: "Grid"
					},
					{
						value: 10,
						text: "Gridnum"
					},
					{
						value: 11,
						text: "Climbing"
					},
					{
						value: 13,
						text: "SwichPractice"
					},
					{
						value: 15,
						text: "Track1"
					},
					{
						value: 16,
						text: "Track2"
					},
				],
				video: [{
						value: 4,
						text: "VideoStraight"
					},
					{
						value: 5,
						text: "VideoCurve"
					},
					{
						value: 17,
						/*  */
						text: "ParallelTurn"
					},
					{
						value: 18,
						text: "WedgeTurn"
					},
					{
						value: 19,
						text: "WedgeChristie"
					},

				],
				animation: [{
						value: 1,
						text: "ShapeGenerator"
					},
					{
						value: 2,
						text: "SinWave"
					},
					{
						value: 6,
						text: "XDistance"
					},
					{
						value: 12,
						text: "CWave"
					},
					{
						value: 14,
						text: "Slalom"
					},

				],
				//slalom
				slalomState: null,
				slalomStateData: [{
						value: [{
								name: "Speed",
								value: 10,
								min: 1,
								max: 25,
								step: 1
							},
							{
								name: "The width of the shape",
								value: 25,
								min: 10,
								max: 300,
								step: 5
							},
							{
								name: "The height of the shape",
								value: 0,
								min: 10,
								max: 300,
								step: 5
							},
							{
								name: "Distance between graphics front and back",
								value: 60,
								min: 30,
								max: 200,
								step: 5
							},
							{
								name: "The graphic's left-right distance (left wide, right tight)",
								value: 20,
								min: 10,
								max: 50,
								step: 1
							}
						],
						text: "state1"
					},
					{
						value: [{
								name: "Speed",
								value: 1,
								min: 1,
								max: 25,
								step: 1
							},
							{
								name: "The width of the shape",
								value: 10,
								min: 10,
								max: 300,
								step: 5
							},
							{
								name: "The height of the shape",
								value: 10,
								min: 10,
								max: 300,
								step: 5
							},
							{
								name: "Distance between graphics front and back",
								value: 30,
								min: 30,
								max: 200,
								step: 5
							},
							{
								name: "The graphic's left-right distance (left wide, right tight)",
								value: 10,
								min: 10,
								max: 50,
								step: 1
							}
						],
						text: "state2"
					}
				],


				// shape_generator
				timestamp: Date.now(),
				double_l: true,
				random_status: false,

				// sinWave
				color: '(255,136,127)',
				//curve
				curveColor: '(255,136,127)',
				shapeGeneratorColor: '(255,136,127)',
				lrReverse: false,
				showScore: false,
				showArUco: false,
				is_generating: false,
				generate_exit: false,

				// singleCurve 8
				isFlipped: false,
				// 13 SwichPractice
				showLogo: false,

				// 8
				bgDisplay: false,


				index_name_map: {
					1: 'ShapeGenerator',
					2: 'SinWave',
					3: 'Maze',
					4: 'VideoStraight',
					5: 'VideoCurve',
					6: 'XDistance',
					7: 'Net',
					8: 'SingleCurve',
					9: 'Grid',
					10: 'Gridnum',
					11: 'Climbing',
					12: 'CWave',
					13: 'SwichPractice',
					14: 'Slalom',
					15: 'Track1',
					16: 'Track2',
					17: 'ParallelTurn',
					18: 'WedgeTurn',
					19: 'WedgeChristie',
				},
			}
		},
		computed: {
			// 根据索引动态获取组件名称
			currentComponent() {
				return this.index_name_map[this.index];
			},
		},
		methods: {
			callChildMethod(is_generating, generate_exit) {
				const childComponent = this.$refs.dynamicChild;
				if (childComponent && childComponent.send) {
					childComponent.send(is_generating, generate_exit); // 传递参数
				} else {
					console.error('子组件未找到或没有 send 方法');
				}
			},
			btnDeleteAllSchema() {
				deleteAllSchemas().then(res => {
					this.cureentSchemas = []
					uni.showToast({
						title: "done"
					})

				})
			},
			updateFromSchema(save_data_str) {
				let compoents_name = this.index_name_map[this.index]
				let obj = this.$t(compoents_name);
				var target_nums = save_data_str.split(',').map(Number);
				for (var i = 0; i < obj.length; i++) {
					obj[i]["value"] = target_nums[i]
				}
			},
			getCurrentAllSchemas() {
				mediaIndexItem(this.index).then(res => {
					var result = []
					for (var i = 0; i < res.length; i++) {
						var data = {
							text: res[i]["plan_name"],
							value: res[i]["save_data_str"]
						}
						result.push(data)
					}


					this.cureentSchemas = result

				})
			},
			saveToSqlLite(plan_name) {
				let compoents_name = this.index_name_map[this.index]
				let saved_data = this.$t(compoents_name);
				// console.log("1111111111111111111111111111111111", saved_data)


				let save_data_str = ''
				for (let i = 0; i < saved_data.length; i++) {
					save_data_str = save_data_str + saved_data[i]['value'].toString()
					if (i != saved_data.length - 1) {
						save_data_str = save_data_str + ","
					}
				}

				// 按照id, media_id, plan_name, save_data_str
				let construct_save_data = {
					media_id: this.index,
					plan_name: plan_name,
					save_data_str
				}
				existSchema(construct_save_data).then(res => {
					var exist = res[0]['count'] > 0
					console.log('exist', exist)
					if (exist) {
						mediaUpdate(construct_save_data)
					} else {
						mediaAdd(construct_save_data)
					}
				})

				// mediaAdd(construct_save_data)

				// NOTE: Do not need this
				mediaAll().then(res => {
					console.log(res, "aaaaaaaaaaaaaaaaaaaaaaaaaaaa")
				})

				this.showSaveSqlLite = false
			},
			goSqlite() {
				const row = {
					animationId: 123,
					animationName: "wangjiangCheng"
				}
				userAdd(row).then(res => {
					console.log(res)
				})
				// const dbName = "ski"
				// closeDb(dbName).then(res => {
				// 	console.log(res,"wwwwwwwwwwwwwwwwwwww")
				// })
				userAll().then(res => {
					console.log(res)
				})

			},
			scanQrCode() {
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_code == 1000) {
							this.ip = ret.resp_result,
								this.saveHostAndPort()
							console.log(this.ip, "this.ip")
							uni.showModal({
								title: "set the IP successfully",
								// 返回值中，resp_code 表示返回结果值，10：用户取消，11：其他错误，1000：成功
								// 返回值中，resp_message 表示返回结果信息
								// 返回值中，resp_result 表示扫码结果（字符串类型），只有成功才会有返回
								content: ret.resp_result,
								showCancel: false,
							})
						} else if (ret.resp_code == 10 || ret.resp_code == 11) {
							uni.showModal({
								title: "Failed to recognize the QR code",
								content: json.stringify(ret),
								// 返回值中，resp_code 表示返回结果值，10：用户取消，11：其他错误，1000：成功
								// 返回值中，resp_message 表示返回结果信息
								// 返回值中，resp_result 表示扫码结果（字符串类型），只有成功才会有返回
							})

						}
					})
			},

			changeSlalomState(e) {
				console.log(e)
				this.Slalom = e

			},

			goToHomePage() {
				uni.navigateTo({
					url: '/pages/index/index' // 假设视频页面的路径是 /pages/index/video
				});
			},
			//不停地获取到消息然后展示消息
			getMessage() {
				uni.request({
					url: `http://${this.ip}:5000/get_message`,
					method: 'GET',
					success: (res) => {
						if (res.statusCode == 200) {
							try {
								const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
								this.message = data.message;
								sleep(10000);
								this.message = 'There is no message in the message queue yet'
							} catch (error) {
								console.error('解析消息失败:', error);
							}
						}
					},
					fail: (res) => {
						// console.log(res, "fail11111111111")
					}
				});
			},
			startPolling() {
				if (!this.pollingInterval) {
					this.getMessage(); // 立即获取一次消息
					this.pollingInterval = setInterval(this.getMessage, 100000); // 每10秒获取一次消息
				}
			},
			stopPolling() {
				if (this.pollingInterval) {
					clearInterval(this.pollingInterval);
					this.pollingInterval = null;
				}
			},

			chooseLanguage() {
				const languageOptions = this.$i18n.availableLocales.map(locale => {
					return {
						text: locale,
						value: locale
					};
				});
				uni.showActionSheet({
					itemList: languageOptions.map(option => option.text),
					success: res => {
						const selectedLanguage = languageOptions[res.tapIndex].value;
						this.$i18n.locale = selectedLanguage;
						const setLangData = selectedLanguage.slice(0, 2)
						console.log(setLangData, "setLangData")
						uni.request({
							url: `http://${this.ip}:5000/setlang`,
							method: 'POST',
							data: setLangData,
							success: (res) => {
								console.log(res, "22222222222222")
							},
							fail: (res) => {
								console.log(res, "fail11111111111")
							},
						});
						uni.setStorageSync('selectedLanguage', selectedLanguage);
						// uni.redirectTo({
						// url: '/pages/index/index', // 替换为目标页面路径
						// });

					}
				});
			},

			saveHostAndPort() {
				let data = `${this.ip}:${this.port}`
				this.saveFile("networkConfig.txt", data, function() {})
			},
			// 读取本地文件的方法 参数1为文件名称，参数2为回调方法用于处理获取到的文件数据
			fetchFileData(fileName, callback) {
				plus.io.requestFileSystem(
					plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
					fs => {
						// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
						fs.root.getFile(fileName, {
							create: true // 文件不存在则创建
						}, fileEntry => {
							// 文件在手机中的路径
							console.log('文件在手机中的路径', fileEntry.fullPath)
							fileEntry.file(function(file) {
								var fileReader = new plus.io.FileReader();
								console.log("getFile:" + JSON.stringify(file));
								fileReader.readAsText(file, "utf-8")
								fileReader.onloadend = function(res) { //读取文件内容成功后的回调事件
									//res.target.result读取到的文件内容信息
									console.log('最后读取文件内容是=======', res.target.result)
									callback(JSON.parse(res.target.result))
								}
							});
						}, e => {
							console.log('报错111', "getFile failed: " + e.message);
						});
					},

					e => {
						console.log('报错222', e.message);
					}
				);
			},
			// 参数1为文件名称 参数2是文件内容 参数3是回调参数		
			saveFile(fileName, fileInfo, callback) {
				// 请求本地文件系统对象
				plus.io.requestFileSystem(
					plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
					fs => {
						// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
						fs.root.getFile(fileName, {
							create: true // 文件不存在则创建
						}, fileEntry => {
							// 文件在手机中的路径
							console.log('最后文件在手机中的路径========', fileEntry.fullPath)
							fileEntry.createWriter(writer => {
								// 写入文件成功完成的回调函数
								writer.onwrite = e => {
									console.log("写入数据成功");
									callback(true)
								};
								// 写入数据
								writer.write(JSON.stringify(fileInfo));
							})
						}, e => {
							callback(false)
							console.log('报错111', "getFile failed: " + e.message);
						});
					},

					e => {
						console.log('报错222', e.message);
						callback(false)
					}
				);
			},
			update() {
				const title = this.language === 'english' ? 'Confirm Software Update' : (this.language === 'spanish' ?
					'Confirmar actualización de software' : '确认更新投影端');
				const content = this.language === 'english' ? 'Are you sure you want to update the projection terminal?' :
					(this.language === 'spanish' ? '¿Está seguro de que desea actualizar el terminal de proyección?' :
						'您确定要更新投影端吗？');
				uni.showModal({
					title: title,
					content: content,
					success: (res) => {
						if (res.confirm) {
							// 用户点击了确定按钮，执行软件更新操作
							uni.request({
								url: `http://${this.ip}:6000/update_software`,
								method: 'POST',
								data: {
									"update_software": true
								},
								success: (res) => {},
								fail: (res) => {},
							});
						} else if (res.cancel) {
							// 用户点击了取消按钮，不执行任何操作
						}
					}
				});
			},
			shutdown() {
				const title = this.language === 'english' ? 'Confirm Shutdown' : (this.language === 'spanish' ?
					'Confirmar Apagado' : '确认关机');
				const content = this.language === 'english' ?
					'Are you sure you want to shut down the projection terminal?' :
					(this.language === 'spanish' ? '¿Está seguro de que desea apagar el terminal de proyección?' :
						'您确定要关闭投影端吗？');

				uni.showModal({
					title: title,
					content: content,
					success: (res) => {
						if (res.confirm) {
							// 用户点击了确定按钮，执行投影端关机操作
							uni.request({
								url: `http://${this.ip}:6000/shutdownsys`,
								method: 'POST',
								data: {
									"shutdownsys": true
								},
								success: (res) => {},
								fail: (res) => {},
							});
						} else if (res.cancel) {
							// 用户点击了取消按钮，不执行任何操作
						}
					}
				});
			},
			restart() {
				const title = this.language === 'english' ? 'Confirm Restart' : (this.language === 'spanish' ?
					'Confirmar Reinicio' : '确认重启');
				const content = this.language === 'english' ? 'Are you sure you want to restart the application?' :
					(this.language === 'spanish' ? '¿Está seguro de que desea reiniciar la aplicación?' : '您确定要重启应用吗？');

				uni.showModal({
					title: title,
					content: content,
					success: (res) => {
						if (res.confirm) {
							// 用户点击了确定按钮，执行应用重启操作
							uni.request({
								url: `http://${this.ip}:6000/restartapp`,
								method: 'POST',
								data: {
									"restartapp": true
								},
								success: (res) => {},
								fail: (res) => {},
							});
						} else if (res.cancel) {
							// 用户点击了取消按钮，不执行任何操作
						}
					}
				});
			},
			screenSet() {
				const title = this.language === 'english' ? 'Screen Settings' : (this.language === 'spanish' ?
					'Configuración de Pantalla' : '屏幕设定');
				const content = this.language === 'english' ? 'Confirm?' : (this.language === 'spanish' ? '¿Confirmar?' :
					'确认吗？');
				uni.showModal({
					title: title,
					content: content,
					success: (res) => {
						if (res.confirm) {
							// 用户点击了确定按钮，执行应用重启操作
							uni.request({
								url: `http://${this.ip}:6000/setPCscreen`,
								method: 'POST',
								data: {
									"setPCscreen": true
								},
								success: (res) => {},
								fail: (res) => {},
							});
						} else if (res.cancel) {
							// 用户点击了取消按钮，不执行任何操作
						}
					}
				});
			},

			changeIp() {
				this.fetchFileData("networkConfig.txt", (res) => {
					if (res !== '') {
						this.ip = res.split(":")[0]
						this.port = res.split(":")[1]
					}
				})
				this.showIp = !this.showIp
			},
			init() {
				// #ifdef APP-PLUS
				this.checkVersion()
				// #endif
			},
			//检查版本更新情况
			checkVersion() {
				//模拟接口获取最新版本号，版本号固定为整数
				setTimeout(() => {
					uni.getSystemInfo({
						success: function(res) {
							console.log(res.appVersionCode)
						}
					});
					// const selfVersionCode = Number(uni.getSystemInfoSync().appId) //当前App版本号
					// console.log(selfVersionCode)

					let platform = uni.getSystemInfoSync().platform //手机平台
					//安卓手机弹窗升级
					if (platform === 'android') {
						uni.navigateTo({
							url: './upgrade'
						})
					}
					//IOS无法在线升级提示到商店下载
					else {
						uni.showModal({
							title: '发现新版本 ',
							content: '请到App store进行升级',
							showCancel: false
						})
					}

				}, 200)
			},
			getZipFiles() {
				this.init()
			},
			aesGcmEncrypt(data, key) {
				// 创建一个随机的初始化向量
				const iv = crypto.randomBytes(12);

				// 创建一个cipher实例用于加密
				const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);

				// 加密数据
				let encrypted = cipher.update(data, 'utf8', 'hex');
				encrypted += cipher.final('hex');

				// 获取认证标签
				const tag = cipher.getAuthTag().toString('hex');

				// 返回IV，加密数据和标签
				return `${iv.toString('hex')}:${encrypted}:${tag}`;
			},
			changeIndex(e) {
				console.log("e:", e);
				this.index = e
				const childComponent = this.$refs.dynamicChild;
				childComponent.send(false, false)
			},
			test() {
				const OSS = require('ali-oss');

				const client = new OSS({
					// yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
					region: 'oss-cn-nanjing',
					// 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
					accessKeyId: 'LTAI5t9XwGGMfZBrXNsa475K',
					accessKeySecret: 'AR2BK9RC8WtLY2eXXx3akJm9ekd8gJ',
					// yourbucketname填写存储空间名称。
					bucket: 'ski-projection-ai'
				});
				const filename = 'ski.apk'
				//这个地方需要拼接下载的文件路径,问后端要
				const response = {
					"content-disposition": "attachment; filename=" + encodeURIComponent(filename),
				};
				//文件名字
				const url = client.signatureUrl(filename, {
					response
				});
				console.log(url, 'url')
				uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.showToast({
								title: '文件下载成功',
								mask: true,
							});
						}
					},
					fail: (error) => {
						uni.hideLoading();
						uni.showToast({
							title: '文件下载失败',
							icon: 'error',
							mask: true,
						});
					}
				});

			},
			send(sendData) {
				const keyBytes = [
					0x2b, 0xad, 0x2e, 0xea, 0x4e, 0x36, 0xcc, 0xf5,
					0x65, 0xba, 0xce, 0xec, 0x6d, 0x3f, 0x18, 0x49,
					0x46, 0x97, 0xd4, 0x44, 0x54, 0x38, 0x57, 0x65,
					0xb8, 0x74, 0xe0, 0x9a, 0x13, 0x4b, 0x97, 0xbc
				]

				// 在Node.js中，您可以使用Buffer
				const key = Buffer.from(keyBytes)
				const encodeSendData = this.aesGcmEncrypt(JSON.stringify(sendData), key)


				// 在这里发送加密数据和IV到服务器
				// 例如使用 axios 或其他 HTTP 客户端
				uni.request({
					url: `http://${this.ip}:${this.port}/receive_data`, //仅为示例，并非真实接口地址。
					method: 'POST',
					timeout: 10000, // 设置超时时间为 10 秒
					data: encodeSendData,
					success: (res) => {
						console.log(res, "请求成功")
					},
					fail: (res) => {
						console.log(res, "请求失败，完整错误信息：", JSON.stringify(res));
					}
				});
			}
		},
		watch: {},
		mounted() {
			// this.test() # 
			this.fetchFileData("networkConfig.txt", (res) => {
				if (res !== '') {
					this.ip = res.split(":")[0]
					this.port = res.split(":")[1]
				}
			})
			const storedLanguage = uni.getStorageSync('selectedLanguage');
			if (storedLanguage) {
				this.$i18n.locale = storedLanguage;
			}
		},
		created() {
			this.startPolling(); // 页面加载时开始获取消息
		},
		onShow() {
			const redirected = getApp().globalData.redirected || false;
			if (!redirected) {
				getApp().globalData.redirected = true;
				// 首次显示页面时，重定向到临时页面
				// uni.redirectTo({
				// 	url: '/pages/index/tem'
				// });
			} else {
				// 返回到主页面后执行的逻辑
				console.log("页面重新加载");
			}
		},
		beforeDestroy() {
			this.stopPolling(); // 页面销毁前停止获取消息
		}
	}
</script>

<style lang="scss" scoped>
	.top-nav {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}
</style>